'''# built_in'''
import os, sys, shutil, argparse
'''# custom'''
from common import *
from product import version


def createFile(root, file, content):
    if os.path.exists(f"{root}\\{file}"):
        print("file already exist ! ")
        sys.exit(0)
    try:
        fileObject = open(f'{root}\\{file}', 'w', encoding="utf-8")
        fileObject.write(content)
        fileObject.close()
    except Exception as error:
        print("Presetting file operation failed ! ")
        sys.exit(2)
    print(f"Creation completed ! ：{root}\{file}")

def run():
    parser = argparse.ArgumentParser()
    parser.add_argument("-n", "--new", action='store_true', help="框架用例数据包生成")
    parser.add_argument("-c", "--change", action='store_true', help="框架自定义配置文件生成")
    parser.add_argument("-p", "--parameter", action='store_true', help="框架静态启动参数文件生成")
    parser.add_argument("--st", action='store_true', help="框架初始化清除脚本生成")
    parser.add_argument("--unit_new", action='store_true', help="框架插件包模板生成")
    parser.add_argument("--unit_show", action='store_true', help="显示框架中目前安装的插件")
    parser.add_argument("--unit_install", metavar='install', action='append', help="框架插件包安装，传入参数为包路径；支持多参数", default=[])
    parser.add_argument("--unit_uninstall", metavar='uninstall', action='append', help="框架插件包卸载，传入参数为插件名；支持多参数", default=[])
    parser.add_argument("-v", "--version", action='version', version=f'kdtest v/{version}', help="显示版本号" )
    parser.add_argument("-s", "--state", metavar='state', nargs='?', help="框架参数配置方法", const='default', default='default', choices=['static', 'default'])
    
    '''对各项进行处理'''
    args = parser.parse_args()
    root = os.getcwd()  # 根目录
    GSDSTORE['WORKPATH'] = {}
    GSDSTORE['WORKPATH']['ROOT'] = root
    if args.new:
        if not os.path.exists(f"{root}\\casesAggregate"):
            os.makedirs(f"{root}\\casesAggregate\\auxiliary_用例辅助数据文件夹")
            os.makedirs(f"{root}\\casesAggregate\\cases_用例步骤文件夹")
            os.makedirs(f"{root}\\casesAggregate\\element_用例元素节点文件夹")
            os.makedirs(f"{root}\\casesAggregate\\interface_用例接口数据文件夹")
            shutil.copy(f"{PROJECTROOT}\\data\\static\\testCases.xlsx", f"{root}\\casesAggregate\\cases_用例步骤文件夹")
            print(f"Creation completed ! ：{root}\casesAggregate")
        else:
            print("folder already exists ! ")
        sys.exit(0)
    
    if args.unit_new:
        if not os.path.exists(f"{root}\\plugins"):
            os.makedirs(f"{root}\\plugins\\CJ_1\\elementData")
            os.makedirs(f"{root}\\plugins\\CJ_1\\utils")
            print(f"Creation completed ! ：{root}\plugins")
            createFile(f"{root}\\plugins\\CJ_1", '__init__.py', "")
            createFile(f"{root}\\plugins\\CJ_1", 'my.ini', INI_CONTENT)
            createFile(f"{root}\\plugins\\CJ_1", 'module.py', MODULE_CONTENT)
            createFile(f"{root}\\plugins\\CJ_1\\elementData", 'elementData.yaml', "")
        else:
            print("folder already exists ! ")
        sys.exit(0)
    
    if args.unit_show:
        pluginsList = os.listdir(f"{PROJECTROOT}\\plugins")
        if pluginsList:
            line = len('----------------------------------------')
            for index, item in enumerate(pluginsList):
                value = len(item)
                if not index:print('----------------------------------------')
                print(f"  Name  |{' '*(int((line-8-value)/2))}{item}{' '*(int((line-8-value)/2))}")
                print('----------------------------------------')
        else:
            print(f"No plug-in is available ! ")
        sys.exit(0) 
    
    if args.unit_install:
        for item in args.unit_install:
            if os.path.exists(item):
                iden = item.split("\\")[-1]
                if not os.path.exists(f"{PROJECTROOT}\\plugins\\{iden}"):
                    shutil.copytree(item, f"{PROJECTROOT}\\plugins\\{iden}")
                else:
                    switch = input(F"The plug-in package has been installed !, Whether to update {item}: Y/N?")
                    if switch.upper() == "Y":
                        shutil.rmtree(f"{PROJECTROOT}\\plugins\\{iden}")
                        shutil.copytree(item, f"{PROJECTROOT}\\plugins\\{iden}")
                        print(f"Plug-in update successful ! {item}")
                        continue
                    else:
                        continue
                print(f"Plug-in installed successfully ! {item}")
            else:
                print(f"File not found: {item}")
                sys.exit(1)
        else:
            sys.exit(0)
    
    if args.unit_uninstall:
        for item in args.unit_uninstall:
            if os.path.exists(f"{PROJECTROOT}\\plugins\\{item}"):
                switch = input(F"Confirm whether to delete the plug-in: {item}: Y/N?")
                if switch.upper() == "Y":
                    shutil.rmtree(f"{PROJECTROOT}\\plugins\\{item}")
                    print(f" √ Plug-in removed: {item}")
            else:
                print(f" × The plug-in was not found : {item}")
                sys.exit(1)
        else:
            sys.exit(0)

    if args.change:
        createFile(root, 'change.py', CHANGE_CONTENT)
        sys.exit(0)
    
    if args.parameter:
        createFile(root, 'parameters.json', PARAMETERS_CONTENT)
        sys.exit(0)
    
    if args.st:
        createFile(root, '__st__.py', ST_CONTENT)
        sys.exit(0)
    
    for item in ["result\\log", "result\\excel", "download"]:
        if not os.path.exists(f'{GSDSTORE["WORKPATH"]["ROOT"]}\\{item}'):
            os.makedirs(f"{GSDSTORE['WORKPATH']['ROOT']}\\{item}")
    
    # 配置方法确定，并执行
    from data.init_data import InitializationParameter
    if args.state in ['static', 'default']:
        print(f"***  Framework implementation: {args.state}  ***")
        try:
            InitializationParameter()(args.state)
        except Exception as error:
            print("Parameter configuration error ! ")
            sys.exit(2)
    
    # 测试环境生成
    from utils.environment_Configuration import EnvironmentConfiguration
    try:
        EnvironmentConfiguration()(GSDSTORE['START']['browser'], GSDSTORE['START']['url'], GSDSTORE['START']['implicitlyWait'])
    except Exception as error:
        print("Environment generation error ! ")
        sys.exit(2)
    
    # 0 表示命令执行成功, 1 表示命令执行有错误, 2 表示框架内部出错
    from utils.log import log
    from cases.case_execution import collector, cases
    collector.run(); cases()()

if __name__ == '__main__':
    sys.exit(run())